package org.brandonep.server.home.log5;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.http.*;

import org.apache.commons.io.FileUtils;
import org.brandonep.server.home.log5.data.CustomDatastore;
import org.brandonep.server.home.log5.data.Device;

import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.google.code.twig.ObjectDatastore;

@SuppressWarnings("serial")
public class DeviceServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		@SuppressWarnings("unchecked")
		HashMap<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap());
		if(params.containsKey("register")){
			resp.setContentType("application/json");
			resp.setCharacterEncoding("UTF-8");
			resp.addHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
			resp.addHeader("Cache-Control", "no-cache, must-revalidate");
			
			String id = IdFactory.generate();
			
			ChannelService channelService = ChannelServiceFactory.getChannelService();
			String token = channelService.createChannel(id);
			
			resp.getWriter().write("{ \"id\": \"" + id + "\", \"token\": \"" + token + "\" }");
			
		}else if(params.containsKey("opened") && params.containsKey("id") && params.containsKey("token")){
			
			Device newDevice = new Device();
			newDevice.id = params.get("id")[0];
			newDevice.token = params.get("token")[0];
			
			ObjectDatastore datastore = new CustomDatastore();
			
			datastore.store(newDevice);
			
			resp.setContentType("application/json");
			resp.addHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
			resp.addHeader("Cache-Control", "no-cache, must-revalidate");
			resp.getWriter().println("{\"status\":\"ok\"}");
			
		}else if(params.containsKey("command") && params.containsKey("id")){

			String id = params.get("id")[0];
			String command = params.get("command")[0];
			
			ChannelService channelService = ChannelServiceFactory.getChannelService();
			String message = "{\"command\":\"" + command + "\"}";
			
			channelService.sendMessage(new ChannelMessage(id, message));
			
			resp.setContentType("application/json");
			resp.addHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
			resp.addHeader("Cache-Control", "no-cache, must-revalidate");
			PrintWriter writer = resp.getWriter();
			writer.print("{\"status\":\"ok\"}");
			
		}else{
			
			resp.setContentType("text/html");
			
			File deviceFile = new File("log5/device.html");
			String deviceHTML = FileUtils.readFileToString(deviceFile);
			
			resp.getWriter().write(deviceHTML);
			
		}
	}
}
